package com.ruoyi.business.service.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.business.domain.Shop;
import com.ruoyi.business.domain.ShopVerification;
import com.ruoyi.business.domain.UserCoupon;
import com.ruoyi.business.mapper.ShopVerificationMapper;
import com.ruoyi.common.security.utils.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import com.ruoyi.business.mapper.CouponMapper;
import com.ruoyi.business.domain.Coupon;
import com.ruoyi.business.service.ICouponService;
import org.springframework.transaction.annotation.Transactional;

/**
 * 平台优惠券Service业务层处理
 * 
 * @author ffc
 * @date 2024-09-12
 */
@Service
public class CouponServiceImpl extends ServiceImpl<CouponMapper,Coupon> implements ICouponService
{
    @Autowired
    private CouponMapper couponMapper;

    @Autowired
    private ShopServiceImpl shopServiceImpl;

    @Autowired
    private UserCouponServiceImpl userCouponService;

    @Autowired
    private RedisTemplate<Object,Object> redisTemplate;

    /**
     * 更新优惠券状态
     *
     * @param
     * @return 优惠券
     */
    public void updateCouponStatus(Coupon coupon, List<Coupon> coupons) {
        if (coupon != null) {
            long timeNow = new Date().getTime();
            long timeEnd = coupon.getEnd().getTime();
            if(timeEnd<=timeNow){
                Coupon newData = new Coupon();
                newData.setStatus(1L);
                couponMapper.updateById(newData);
            }
        }else{
            List<Long> ids = new ArrayList<>();
            for (Coupon item:coupons) {
                long timeNow = new Date().getTime();
                long timeEnd = item.getEnd().getTime();
                if(timeEnd<=timeNow){
                    ids.add(item.getId());
                }
            }
            if (ids.size()==0) {
                return;
            }
            Coupon newData = new Coupon();
            newData.setStatus(1L);
            QueryWrapper<Coupon> queryWrapper = new QueryWrapper<>();
            queryWrapper.in("id",ids);
            couponMapper.update(newData,queryWrapper);
        }
    }


    /**
     * 查询平台优惠券
     * 
     * @param id 平台优惠券主键
     * @return 平台优惠券
     */
    @Override
    public Coupon selectCouponById(Long id)
    {
        Coupon coupon = couponMapper.selectCouponById(id);
        if(coupon.getDiscount()!=null){
            coupon.setDiscount(coupon.getDiscount()*10);
        }
        updateCouponStatus(coupon,null);
        if(coupon.getDiscount()!=null){
            coupon.setDiscount(coupon.getDiscount()*10.0);
        }
        return coupon;
    }


    /**
     * 查询平台优惠券列表
     * 
     * @param coupon 平台优惠券
     * @return 平台优惠券
     */
    @Override
    public List<Coupon> selectCouponList(Coupon coupon)
    {
        List<Coupon> coupons = couponMapper.selectCouponList(coupon);
        for (Coupon item:coupons) {
            if(item.getSource()==null || item.getSource()==1){
                Shop shop = shopServiceImpl.selectShopById(item.getMid());
                item.setShop(shop);
            }
        }
        updateCouponStatus(null,coupons);
        for (Coupon item :coupons) {
            if(item.getDiscount()!=null){
                item.setDiscount(item.getDiscount()*10.0);
            }
        }
        return coupons;
    }

    /**
     * 新增平台优惠券
     * 
     * @param coupon 平台优惠券
     * @return 结果
     */
    @Override
    public int insertCoupon(Coupon coupon)
    {
        if(coupon.getDiscount()!=null){
            coupon.setDiscount(coupon.getDiscount()/10.0);
        }
        int num = couponMapper.insertCoupon(coupon);
        redisTemplate.opsForHash().put("coupon",String.valueOf(coupon.getId()),coupon.getNum());
        return num;
    }

    /**
     * 修改平台优惠券
     * 
     * @param coupon 平台优惠券
     * @return 结果
     */
    @Transactional
    @Override
    public synchronized int updateCoupon(Coupon coupon)
    {
        if(coupon.getDiscount()!=null){
            coupon.setDiscount(coupon.getDiscount()/10.0);
        }
        if (coupon.getNum() == 0) {
            coupon.setStatus(1L);
            redisTemplate.opsForHash().delete("coupon",String.valueOf(coupon.getId()));
        }else{
            coupon.setStatus(0L);
            redisTemplate.opsForHash().put("coupon",String.valueOf(coupon.getId()),coupon.getNum());
        }
        return couponMapper.updateCoupon(coupon);
    }

    /**
     * 领取优惠券
     *
     * @param id 优惠券id
     * @return 结果
     */
    @Override
    public synchronized int getCoupon(Long id,Long uId) {
        Object couponNum = redisTemplate.opsForHash().get("coupon", String.valueOf(id));
        long num = Long.parseLong(couponNum.toString());
        if (num == 0) {
            Coupon coupon = new Coupon();
            coupon.setId(id);
            coupon.setNum(0L);
            couponMapper.updateCoupon(coupon);
        }
        //领取前查询是否领取
        UserCoupon userCoupon = new UserCoupon();
        userCoupon.setuId(uId);
        userCoupon.setcId(id);
        List<UserCoupon> list = userCouponService.findList(userCoupon);
        if(list.size()!=0){
            return 0;
        }
        Date now = new Date();
        long twoMonthsInMillis = 2 * 30 * 24 * 60 * 60 * 1000L;
        Date twoMonthsLater = new Date(now.getTime() + twoMonthsInMillis);
        userCoupon.setExpirationStart(now);
        userCoupon.setExpirationEnd(twoMonthsLater);
        userCouponService.insertUserCoupon(userCoupon);
        redisTemplate.opsForHash().put("coupon", String.valueOf(id), num-1);
        return 1;
    }

    /**
     * 批量删除平台优惠券
     * 
     * @param ids 需要删除的平台优惠券主键
     * @return 结果
     */
    @Override
    public synchronized int deleteCouponByIds(Long[] ids)
    {
        for (Long id:ids) {
            redisTemplate.opsForHash().delete("coupon",id.toString());
        }
        return couponMapper.deleteCouponByIds(ids);
    }

    /**
     * 删除平台优惠券信息
     * 
     * @param id 平台优惠券主键
     * @return 结果
     */
    @Override
    public synchronized int deleteCouponById(Long id)
    {
        redisTemplate.opsForHash().delete("coupon",id.toString());
        return couponMapper.deleteCouponById(id);
    }
}
